﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeBuilder2.Model;
using CodeBuilder2.DAL.Connection;
using System.Data.Common;

namespace CodeBuilder2.BLL.Connection
{
    class ConnectionHelper
    {
        static ConnectionDAL cDal = new ConnectionDAL();

        public static bool Connect(TargetServer ts)
        {
            // 或许可以考虑使用 DbConnectionStringBuilder 或者它的子类来构造连接字符串，
            // 不过这样一来 DBManager 类又需要修改，如何改甚至是否还需要这个类目前还都没有考虑成熟

            bool flag = false;

            DbConnection dbConn = cDal.CreateConnection(ts);
            if (dbConn != null)
            {
                try
                {
                    dbConn.Open();
                    //System.Data.SqlClient.SqlDataAdapter ada = new System.Data.SqlClient.SqlDataAdapter("select * from sysobjects", dbConn as System.Data.SqlClient.SqlConnection);
                    //System.Data.DataTable dt = new System.Data.DataTable();
                    //ada.Fill(dt);
                    flag = true;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    dbConn.Close();
                }
            }

            return flag;
        }

        /// <summary>
        /// 获得所有当前已经连接的服务器的名称
        /// </summary>
        /// <returns>当前已经连接的服务器的名称</returns>
        public static List<string> GetConnectedServersName()
        {
            var names = from key in cDal.GetConnectedServers().Keys
                        select key;
            //List<string> lNames = new List<string>(names.Count()); // 得到的 Count 是 0，有问题
            List<string> lNames = new List<string>();
            foreach (var item in names)
            {
                lNames.Add(item);
            }
            return lNames;
        }

        public static bool ChangeDataBase(string serverName, string dataBaseName)
        {
            bool flag = false;
            TargetServer ts = cDal.GetConnectedServers()[serverName];
            ts.DataBase = dataBaseName;
            flag = Connect(ts);
            return flag;
        }
    }
}
